package com.zh.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author :fjw
 * @description:TODO
 * @date :2020/10/18 17:20
 */
//AOP,拦截器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	//授权
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//首页所有人可以访问，功能页只有对应有权限的人才能访问
		http.authorizeRequests()
				//放行所有
				.antMatchers("/").permitAll()
				.antMatchers("/test/**").hasAnyRole("vip1","vip2")
				//没有权限会跳转到登录页，开启登录页面，security自带,/login
				.and().formLogin();

		//http.formLogin().loginPage("/myLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");//定制登录页

		//开启注销功能,security自带/logout页面
		http.logout().logoutSuccessUrl("/");//默认重新登录页，修改到首页

		//CSRF一般指跨站请求伪造Cross-site request forgery），
		//也被称为 one-click attack 或者 session riding
		http.csrf().disable();//防止网站攻击：get,post，关闭csrf功能，登录失败可能存在的原因

		//退出清空session
		//http.logout().deleteCookies("remove").invalidateHttpSession(true);


		//开启记住我功能,cookie中,默认保存两周
		http.rememberMe()
				//接受单选框的name参数名
		.rememberMeParameter("remenber");

	}

	//认证,springboot 2.1.x 可以直接使用
	//密码编码：PasswordEncoder
	//在spring security 5.0+ 新增了很多的加密方法
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//这些数据正常应该从数据库中读
		auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
				.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
				.and()
				.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
				.and()
				.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");


		//auth.jdbcAuthentication();数据库授权
	}
}
